package com.leyou.user.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProp;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);
        //判空
        if(StringUtils.isEmpty(token)){
            log.error("【用户微服务校验来访服务权限】失败！来访服务没有携带token！");
            return false;
        }
        Payload<AppInfo> payload = null;
        //解析token
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            log.error("【用户微服务校验来访服务权限】失败！来访服务携带的token不合法！");
            return false;
        }
        //查看来访服务是否有访问权限
        if(!payload.getUserInfo().getTargetList().contains(jwtProp.getApp().getId())){
            log.error("【用户微服务校验来访服务权限】失败！来访服务没有权限！");
            return false;
        }
        log.info("【用户微服务校验来访服务权限】成功！");
        return true;
    }

}
